package com.zjj.distributed.zk.client;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * @author zhanglei.zjj
 * @description 使用 zookeeper 原生 API,连接zookeeper集群
 * @date 2023/6/18 16:40
 */
public class ZkClientDemo {
    private static final String CONNECT_STR = "192.168.200.129:2181";
    private final static String CLUSTER_CONNECT_STR = "192.168.65.156:2181,192.168.65.190:2181,192.168.65.200:2181";

    public static void main(String[] args) throws Exception {

        final CountDownLatch countDownLatch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper(CONNECT_STR, 4000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (Event.KeeperState.SyncConnected == event.getState()
                        && event.getType() == Event.EventType.None) {
                    //如果收到了服务端的响应事件，连接成功
                    countDownLatch.countDown();
                    System.out.println("连接建立");
                }
            }
        });
        System.out.println("连接中");
        countDownLatch.await();
        //CONNECTED
        System.out.println(zooKeeper.getState());

        Stat stat = zooKeeper.exists("/javaClient", false);
        if (stat == null) {
            //创建持久节点
            zooKeeper.create("/javaClient", "zjj".getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        // 持久监听
        zooKeeper.addWatch("/javaClient", new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event);
            }
        },AddWatchMode.PERSISTENT);

        Thread.sleep(Integer.MAX_VALUE);
    }
}
